package com.tuanzi.loan.web.bean.wechat;

import com.base.common.log.LogService;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.starbaba.model.utils.HttpConnectionUtils;
import com.starbaba.model.utils.JSONUtils;
import com.tuanzi.loan.business.entity.wechat.LoanWechatCustomerMessage;
import com.tuanzi.loan.business.service.wechat.WechatCustomerMessageService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.exception.ValidateException;
import com.tuanzi.loan.vo.request.wechat.WechatCustomerMessageManageRequest;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import com.tuanzi.server.loan_base.constant.weixin.LoanWechatCustomerMessageMsgType;
import com.tuanzi.server.loan_base.model.bean.wechat.customermessage.ImageCustomerMessageContent;
import com.tuanzi.server.loan_base.model.bean.wechat.customermessage.NewsCustomerMessageContent;
import com.tuanzi.server.loan_base.model.bean.wechat.customermessage.TextCustomerMessageContent;
import com.tuanzi.server.loan_base.model.request.wechat.UploadPermanentImageRequest;
import com.tuanzi.server.loan_base.model.response.commom.Result;
import com.tuanzi.server.loan_base.model.response.commom.ResultUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.Date;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @Author: chenweijun
 * @Date: 2018/9/28 11:41
 * @Description: 微信公众号客服消息管理Bean
 */
@Data
@Debug
@Component
@ViewScoped
@Slf4j
@EqualsAndHashCode(callSuper = true)
public class WechatCustomerMessageManageBean extends JSFInfoBean<WechatCustomerMessageManageRequest> {

    @Autowired
    private WechatCustomerMessageService wechatCustomerMessageService;

    private LoanWechatCustomerMessage loanWechatCustomerMessage;

    @Value("${upload-permanent-image-url}")
    private String uploadPermanentImageUrl;

    @PostConstruct
    private void init() {

        $ = new WechatCustomerMessageManageRequest();
        String id = getParamFromRequest("id");
        if(StringUtils.isNotBlank(id)){

            loanWechatCustomerMessage = wechatCustomerMessageService.findOne(NumberUtils.toLong(id));
            $.setId(loanWechatCustomerMessage.getId());
            $.setName(loanWechatCustomerMessage.getName());
            $.setProductId(loanWechatCustomerMessage.getProductId());
            $.setEffectiveStartTime(loanWechatCustomerMessage.getEffectiveStartTime());
            $.setEffectiveEndTime(loanWechatCustomerMessage.getEffectiveEndTime());
            $.setTriggerBehavior(loanWechatCustomerMessage.getTriggerBehavior());
            $.setTriggerTime(loanWechatCustomerMessage.getTriggerTime());
            $.setMsgType(loanWechatCustomerMessage.getMsgType());

            if($.getMsgType().equals(LoanWechatCustomerMessageMsgType.TEXT.getValue())){

                TextCustomerMessageContent textContent = JSONUtils.fromJsonNew(loanWechatCustomerMessage.getMsgContent(), TextCustomerMessageContent.class);
                $.setContent(textContent.getContent());
            }else if($.getMsgType().equals(LoanWechatCustomerMessageMsgType.IMAGE.getValue())){

                ImageCustomerMessageContent imageContent = JSONUtils.fromJsonNew(loanWechatCustomerMessage.getMsgContent(), ImageCustomerMessageContent.class);
                $.setPicUrl(imageContent.getPicurl());

            }else if($.getMsgType().equals(LoanWechatCustomerMessageMsgType.NEWS.getValue())){

                List<NewsCustomerMessageContent> newsContents = JSONUtils.fromJsonArrayNew(loanWechatCustomerMessage.getMsgContent(), NewsCustomerMessageContent.class);

                NewsCustomerMessageContent  newsContent= newsContents.get(0);
                $.setPicUrl(newsContent.getPicurl());
                $.setTitle(newsContent.getTitle());
                $.setDescription(newsContent.getDescription());
                $.setUrl(newsContent.getUrl());
            }else if($.getMsgType().equals(LoanWechatCustomerMessageMsgType.NO_PICTURE_NEWS.getValue())){

                List<NewsCustomerMessageContent> newsContents = JSONUtils.fromJsonArrayNew(loanWechatCustomerMessage.getMsgContent(), NewsCustomerMessageContent.class);

                NewsCustomerMessageContent  newsContent= newsContents.get(0);
                $.setTitle(newsContent.getTitle());
                $.setDescription(newsContent.getDescription());
                $.setUrl(newsContent.getUrl());

            }
        }else {
            changeStatusToAdd();
        }

    }

    /**
     * 上传图片到七牛
     * @param event
     */
    public void uploadImage(FileUploadEvent event) {
        String picUrl = this.uploadImg(event.getFile());
        $.setPicUrl(picUrl);

        //上传图片素材到微信服务器
        if($.getMsgType().equals(LoanWechatCustomerMessageMsgType.IMAGE.getValue())){

            if(StringUtils.isBlank($.getProductId())){
                addErrorMessage("请选择公众号");
                return;
            }

            UploadPermanentImageRequest uploadPermanentImageRequest = new UploadPermanentImageRequest();

            uploadPermanentImageRequest.setProductId($.getProductId());
            uploadPermanentImageRequest.setImageUrl(picUrl);
            String responseJson = HttpConnectionUtils.connection(uploadPermanentImageUrl, HttpConnectionUtils.POST, new Gson().toJson(uploadPermanentImageRequest));
            log.info("图片：" + $.getPicUrl() + " 请求上传素材接口响应参数：" + responseJson);
            Result result = new Gson().fromJson(responseJson, Result.class);
            if(ResultUtils.isSuccess(result)){
                String mediaId = (String) result.getData();
                $.setMediaId(mediaId);
                addSuccessfullyMessage();
            }else {
                addErrorMessage("上传图片素材失败");
            }
        }else if($.getMsgType().equals(LoanWechatCustomerMessageMsgType.NEWS.getValue())){
            addSuccessfullyMessage();
        }else{
            addErrorMessage("请选择消息类型");
        }

    }


    public void onSave(){

        if(StringUtils.isBlank($.getName())){
            throw new ValidateException("请输入消息名");
        }

        if(StringUtils.isBlank($.getProductId())){
            throw new ValidateException("请选择公众号");
        }

        Date effectiveStartTime = $.getEffectiveStartTime();
        Date effectiveEndTime = $.getEffectiveEndTime();
        if (effectiveStartTime != null && effectiveEndTime!=null){
            if (effectiveStartTime.compareTo(effectiveEndTime) >=0) {
                throw new ValidateException("生效开始时间大于或等于结束时间");
            }
        }
        else if (effectiveStartTime != null && effectiveEndTime==null){
            throw new ValidateException("生效结束时间不能为空");
        }
        else if (effectiveStartTime == null && effectiveEndTime != null){
            throw new ValidateException("生效开始时间不能为空");
        }

        if($.getTriggerBehavior() == null){
            throw new ValidateException("请选择触发行为");
        }

        if($.getTriggerTime() == null){
            throw new ValidateException("请选择触发时间");
        }

        if(StringUtils.isBlank($.getMsgType())){
            throw new ValidateException("请选择消息类型");
        }


        if(StringUtils.isBlank($.getProductId())){
            throw new ValidateException("请选择公众号");
        }

        if($.getMsgType().equals(LoanWechatCustomerMessageMsgType.TEXT.getValue())){
            if(StringUtils.isBlank($.getContent())){
                throw new ValidateException("请输入文本消息");
            }
        }

        System.out.println("$= " + new Gson().toJson($));
        if($.getMsgType().equals(LoanWechatCustomerMessageMsgType.IMAGE.getValue())){
            if(StringUtils.isBlank($.getPicUrl()) || StringUtils.isBlank($.getMediaId())){
                throw new ValidateException("请上传图片");
            }
        }

        if($.getMsgType().equals(LoanWechatCustomerMessageMsgType.NEWS.getValue())){
            if(StringUtils.isBlank($.getPicUrl())){
                throw new ValidateException("请上传图片");
            }

            if(StringUtils.isBlank($.getTitle())){
                throw new ValidateException("请输入图文标题");
            }

            if(StringUtils.isBlank($.getDescription())){
                throw new ValidateException("请输入图文描述");
            }

            if(StringUtils.isBlank($.getUrl())){
                throw new ValidateException("请输入图文跳转链接");
            }
        }

        if($.getMsgType().equals(LoanWechatCustomerMessageMsgType.NO_PICTURE_NEWS.getValue())){
            if(StringUtils.isBlank($.getTitle())){
                throw new ValidateException("请输入图文标题");
            }

            if(StringUtils.isBlank($.getDescription())){
                throw new ValidateException("请输入图文描述");
            }

            if(StringUtils.isBlank($.getUrl())){
                throw new ValidateException("请输入图文跳转链接");
            }
        }

        wechatCustomerMessageService.saveLoanWechatCustomerMessage($);
        addSuccessfullyMessage();
        changeStatusToView();

    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(WECHAT_OFFICIAL_ACCOUNT, WECHAT_CUSTOMER_MESSAGEA_STATUS, WECHAT_CUSTOMER_MESSAGE_TRIGGER_BEHAVIOR,
                WECHAT_CUSTOMER_MESSAGE_TRIGGER_TIME, WECHAT_CUSTOMER_MESSAGE_MSG_TYPE);
    }

    public boolean showText(){
        return StringUtils.isNotBlank($.getMsgType()) && $.getMsgType().equals(LoanWechatCustomerMessageMsgType.TEXT.getValue());
    }

    public boolean showImage(){
        return StringUtils.isNotBlank($.getMsgType()) && (
                $.getMsgType().equals(LoanWechatCustomerMessageMsgType.IMAGE.getValue())
                        || $.getMsgType().equals(LoanWechatCustomerMessageMsgType.NEWS.getValue()));
    }

    public boolean showNews(){
        return StringUtils.isNotBlank($.getMsgType()) && (
                $.getMsgType().equals(LoanWechatCustomerMessageMsgType.NEWS.getValue())
                        || $.getMsgType().equals(LoanWechatCustomerMessageMsgType.NO_PICTURE_NEWS.getValue()));
    }


}
